package com.sc.nft.consume;

import cn.hutool.core.util.StrUtil;
import com.sc.nft.dto.UserEcologyHatchRecordsDao;
import com.sc.nft.entity.UserEcologyHatchRecords;
import com.sc.nft.enums.MessageTopic;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.EcologySmeltingService;
import com.sc.nft.util.WeChatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@RocketMQMessageListener(topic = MessageTopic.ECOLOGY_HATCH_DIVIDE_INTO_TOPIC + "${spring.profiles.active}", consumerGroup = MessageTopic.ECOLOGY_HATCH_DIVIDE_INTO_TOPIC + "${spring.profiles.active}")
@Component
@Slf4j
@RequiredArgsConstructor
public class EcologyHatchDivideIntoConsumer implements RocketMQListener<UserEcologyHatchRecords> {

    private final Redisson redisson;
    private final RedisTemplate redisTemplate;
    private final EcologySmeltingService ecologySmeltingService;
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;

    @Override
    public void onMessage(UserEcologyHatchRecords userEcologyHatchRecords) {
        try {
            Thread.sleep(4000);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("熔炼 分成处理：记录id:{},熔炼配置id:{}", userEcologyHatchRecords.getId(),userEcologyHatchRecords.getEcologyHatchId());

        String key = RedisKeyEnum.ECOLOGY_HATCH_DIVIDE_INTO_TOPIC_LOCK.getKey() + userEcologyHatchRecords.getId();
        RLock lock = redisson.getLock(key);

        try {
            boolean res = lock.tryLock(3, TimeUnit.SECONDS);
            if (!res){
               throw new GlobalException("积分分成正在处理");
            }
            UserEcologyHatchRecords userEcologyHatchRecordsDaoById = userEcologyHatchRecordsDao.getById(userEcologyHatchRecords.getId());
            log.info("熔炼-分成处理 记录id:{},查询结果:{}", userEcologyHatchRecords.getId(),userEcologyHatchRecordsDaoById);
            ecologySmeltingService.newDivideInto(userEcologyHatchRecordsDaoById);
        } catch (Exception e) {
            WeChatUtil.sendLiGenWeChatMessage(StrUtil.format("熔炼-分成处理失败 记录id：{},异常:{}", userEcologyHatchRecords.getId(), e.getMessage()));
            log.error("熔炼-分成处理失败 记录id：{},异常:{}", userEcologyHatchRecords.getId(), e.getMessage());
        }finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
